package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(path = "/sms")
@SuppressWarnings("all")
public class SmsController {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 健康预约时发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendCode")
    public Result sendCode(String phone) {
        //  String numeric = RandomStringUtils.randomNumeric(6);
        try {
            //防止重复获取验证码
            String ORDER_CODE = "REDIS_ORDER_CODE" + phone;
            if (this.redisTemplate.hasKey(ORDER_CODE)) {
                return new Result(false, MessageConstant.VALIDATECODE_NOTTIMEOUT);
            }
            //生成6位随机数字验证码
            String numeric = "123456";
            //存入redis中
            this.redisTemplate.opsForValue().set(ORDER_CODE, numeric, 300, TimeUnit.SECONDS);

            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendLoginCode")
    public Result sendLoginCode(String phone) {
        //生成6位随机数字验证码
        // String numeric = RandomStringUtils.randomNumeric(6);
        try {
            //防止重复获取验证码
            String LOGIN_CODE = "REDIS_LOGIN_CODE" + phone;
            if (this.redisTemplate.hasKey(LOGIN_CODE)) {
                return new Result(false, MessageConstant.VALIDATECODE_NOTTIMEOUT);
            }

            String numeric = "123456";
            //将验证码存入redis中 300s存活时间
            this.redisTemplate.opsForValue().set(LOGIN_CODE, numeric, 300, TimeUnit.SECONDS);
            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
